package site.icesky.springboot.rocketmq.service;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;

import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.rocketmq.common.message.Message;

/**
 * @ClassName: MqProducerService <br>
 * @Description: 消息生产 <br>
 * @Package: site.icesky.springboot.rocketmq.service <br>
 * @author: suitianmou <br>
 * @Date: 2020/5/24-11:29 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Service
public class MqProducerService {
    private static final Logger logger = LoggerFactory.getLogger(MqProducerService.class);

    @Autowired
    DefaultMQProducer defaultMQProducer;

    @Value("${rocketmq.producer.topic}")
    private String topic;

    public boolean sendMessage(String message){
        Message msg = new Message(topic, "tag", message.getBytes());

        try{
            SendResult sendResult = defaultMQProducer.send(msg);
            if( sendResult.getSendStatus() == SendStatus.SEND_OK ){
                logger.info("发送成功:{}", message);
            } else {
                //    SEND_OK,
                //    FLUSH_DISK_TIMEOUT,
                //    FLUSH_SLAVE_TIMEOUT,
                //    SLAVE_NOT_AVAILABLE;
                logger.error("发送失败，状态是" + sendResult.getSendStatus());
                return false;
            }
        }catch (MQClientException e) {
            logger.error("MQClientException-{}", e);
            return false;
        } catch (InterruptedException e) {
            logger.error("InterruptedException-{}", e);
            return false;
        } catch (RemotingException e) {
            logger.error("RemotingException-{}", e);
            return false;
        } catch (MQBrokerException e) {
            logger.error("MQBrokerException-{}", e);
            return false;
        }
        return true;
    }
}
